<script setup>
import { ref, onMounted } from 'vue'

// 爬取相关数据
const supplierName = ref('')
const supplierPage = ref('')
const loading = ref(false)
const result = ref(null)
const error = ref('')
const logs = ref([])
// 商品选择相关
const selectedProducts = ref([])
const selectAll = ref(false)
// Cookie相关
const savedCookies = ref('')
const useSavedCookies = ref(false)
const showCookieInput = ref(false)

// 组件挂载时从localStorage加载保存的cookie
onMounted(() => {
  const saved = localStorage.getItem('crawlerCookies')
  if (saved) {
    savedCookies.value = saved
    useSavedCookies.value = true
  }
})

// 开始爬取
const startCrawling = async () => {
  // 通用爬取验证
  if (!supplierName.value) {
    error.value = '请输入供应商名称'
    return
  }
  if (!supplierPage.value) {
    error.value = '请输入供应商页面'
    return
  }
  
  loading.value = true
  error.value = ''
  logs.value = []
  result.value = null
  
  try {
    // 调用后端API进行爬取
    logs.value.push('正在发送请求到后端API（通用爬取）...')
    
    // 通用爬取模式
    const endpoint = '/api/crawler/crawl'
    const params = {
      supplierName: supplierName.value,
      supplierUrl: supplierPage.value
    }
    
    // 如果用户选择使用保存的cookie，则添加到请求中
    if (useSavedCookies.value && savedCookies.value) {
      params.cookies = savedCookies.value
      logs.value.push('正在使用已保存的Cookie')
    } else if (showCookieInput.value && savedCookies.value) {
      params.cookies = savedCookies.value
      logs.value.push('正在使用手动输入的Cookie')
    }
    
    logs.value.push(`请求URL: ${endpoint}`)
    logs.value.push(`请求参数: ${JSON.stringify(params)}`)
    
    const response = await fetch(endpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: new URLSearchParams(params)
    })
    
    logs.value.push(`接收到后端响应，状态码: ${response.status}`)
    
    // 检查响应是否被网络错误中断
    if (!response) {
      throw new Error('响应为空，可能是网络中断或服务器无响应')
    }
    
    if (!response.ok) {
      // 尝试获取错误响应内容
      let errorBody
      try {
        errorBody = await response.text()
        logs.value.push(`错误响应内容: ${errorBody}`)
      } catch (parseError) {
        logs.value.push('无法解析错误响应内容')
      }
      throw new Error(`HTTP error! status: ${response.status}, content: ${errorBody || '无内容'}`)
    }
    
    // 检查响应类型
    const contentType = response.headers.get('content-type')
    logs.value.push(`响应类型: ${contentType}`)
    
    // 解析响应数据
    let data
    try {
      data = await response.json()
      logs.value.push('成功解析响应数据')
    } catch (parseError) {
      const rawText = await response.text()
      logs.value.push(`JSON解析失败，原始响应: ${rawText}`)
      throw new Error(`无法解析JSON响应: ${parseError.message}`)
    }
    
    // 更新日志
    if (data.logs && Array.isArray(data.logs)) {
      logs.value = data.logs
    }
    
    if (data.success) {
      logs.value.push(`成功爬取到 ${data.products ? data.products.length : 0} 个商品`)
      
      // 保存返回的cookie（如果有）
      if (data.cookies && data.cookies.length > 0) {
        savedCookies.value = data.cookies
        localStorage.setItem('crawlerCookies', data.cookies)
        useSavedCookies.value = true
        logs.value.push('Cookie已自动保存，下次爬取将自动使用')
      }
      
      // 整理爬取结果
      result.value = {
        supplierName: data.supplierName,
        products: data.products || [],
        totalCount: data.products ? data.products.length : 0,
        cookies: data.cookies
      }
    } else {
      error.value = data.error || '爬取失败'
      logs.value.push('爬取失败: ' + (data.error || '未知错误'))
    }
  } catch (err) {
    const errorMsg = '请求失败: ' + err.message
    error.value = errorMsg
    logs.value.push(errorMsg)
  } finally {
    loading.value = false
    logs.value.push('请求处理完成')
  }
}

// 清空结果
const clearResult = () => {
  result.value = null
  logs.value = []
  error.value = ''
}

// 清除保存的cookie
const clearCookies = () => {
  savedCookies.value = ''
  useSavedCookies.value = false
  localStorage.removeItem('crawlerCookies')
  logs.value.push('已清除保存的Cookie')
}

// 切换显示cookie输入框
const toggleCookieInput = () => {
  showCookieInput.value = !showCookieInput.value
}

// 保存商品
const saveProduct = () => {
  if (selectedProducts.value.length === 0) {
    alert('请先选择要保存的商品')
    return
  }
  
  // 这里将来会调用后端API保存选中的商品
  alert(`已选择 ${selectedProducts.value.length} 个商品，准备保存`)  
  
  // 实际实现时，这里会调用后端API
  // 可以根据商品索引或其他唯一标识符找到对应的商品
  const productsToSave = selectedProducts.value.map(index => result.value.products[index])
}

// 切换单个商品的选中状态
const toggleProductSelection = (index) => {
  const productIndex = selectedProducts.value.indexOf(index)
  if (productIndex > -1) {
    selectedProducts.value.splice(productIndex, 1)
    selectAll.value = false // 取消全选状态
  } else {
    selectedProducts.value.push(index)
    // 检查是否所有商品都已选中
    if (selectedProducts.value.length === result.value.products.length) {
      selectAll.value = true
    }
  }
}

// 切换全选状态
const toggleSelectAll = () => {
  selectAll.value = !selectAll.value
  if (selectAll.value) {
    // 全选：添加所有商品索引
    selectedProducts.value = Array.from({ length: result.value.products.length }, (_, i) => i)
  } else {
    // 取消全选：清空选中列表
    selectedProducts.value = []
  }
}
</script>

<template>
  <div class="product-crawler">
    <div class="panel">
      <div class="panel-header">
        <h3>商品信息爬取</h3>
      </div>
      <div class="panel-body">
        <!-- 爬取表单 -->
        <div class="crawl-form">
          <!-- 通用爬取字段 -->
          <div>
            <div class="form-group">
              <label for="supplierName">供应商名称</label>
              <input 
                id="supplierName"
                v-model="supplierName" 
                type="text" 
                placeholder="请输入供应商名称..." 
                class="form-input full-width"
                :disabled="loading"
              >
            </div>
            <div class="form-group">
              <label for="supplierPage">供应商页面</label>
              <input 
                id="supplierPage"
                v-model="supplierPage" 
                type="text" 
                placeholder="请输入要爬取的供应商页面链接..." 
                class="form-input full-width"
                :disabled="loading"
              >
            </div>
          </div>
          
          <!-- Cookie相关设置 -->
          <div class="form-group">
            <div class="cookie-controls">
              <label class="checkbox-label">
                <input 
                  type="checkbox" 
                  v-model="useSavedCookies" 
                  :disabled="loading || !savedCookies.value"
                >
                使用保存的Cookie（自动登录）
              </label>
              <button 
                @click="toggleCookieInput" 
                class="btn btn-small"
                :disabled="loading"
              >
                {{ showCookieInput ? '隐藏Cookie' : '手动输入Cookie' }}
              </button>
              <button 
                @click="clearCookies" 
                class="btn btn-small btn-warning"
                :disabled="loading || !savedCookies.value"
                title="清除已保存的Cookie"
              >
                清除Cookie
              </button>
            </div>
            
            <!-- 手动输入Cookie区域 -->
            <div v-if="showCookieInput" class="cookie-input-container">
              <textarea 
                v-model="savedCookies" 
                placeholder="请输入Cookie（多个Cookie用分号分隔）..." 
                class="form-input full-width"
                rows="3"
                :disabled="loading"
              ></textarea>
              <p class="hint-text">输入Cookie后，下次爬取将自动使用这些Cookie进行登录</p>
            </div>
            
            <!-- Cookie状态提示 -->
            <div v-if="savedCookies.value && !showCookieInput" class="cookie-status">
              ✓ 已保存Cookie，{{ useSavedCookies ? '将在本次爬取中使用' : '未选择使用' }}
            </div>
          </div>
          
          <div class="form-actions">
            <button 
              @click="startCrawling" 
              class="btn btn-primary" 
              :disabled="loading"
            >
              {{ loading ? '爬取中...' : '开始爬取' }}
            </button>
            <button 
              @click="clearResult" 
              class="btn btn-secondary" 
              :disabled="loading"
            >
              清空
            </button>
          </div>
        </div>

        <!-- 爬取日志 -->
        <div v-if="logs.length > 0" class="crawl-logs">
          <h4>爬取日志</h4>
          <div class="logs-container">
            <p v-for="(log, index) in logs" :key="index" class="log-item">
              {{ log }}
            </p>
          </div>
        </div>

        <!-- 爬取错误 -->
        <div v-if="error" class="error">
          {{ error }}
        </div>

        <!-- 爬取结果 -->
        <div v-if="result" class="crawl-result">
          <div class="result-header">
            <div class="header-left">
              <label class="checkbox-label">
                <input 
                  type="checkbox" 
                  v-model="selectAll" 
                  @change="toggleSelectAll"
                >
                全选 (已选择: {{ selectedProducts.length }})
              </label>
              <h4>爬取结果 - {{ result.supplierName }} (共 {{ result.totalCount }} 件商品)</h4>
            </div>
            <button @click="saveProduct" class="btn btn-success">保存选中商品</button>
          </div>
          
          <div class="result-content">
            <div v-if="result.products && result.products.length > 0" class="products-grid">
              <div v-for="(product, index) in result.products" :key="index" class="product-card">
                <div class="product-checkbox">
                  <input 
                    type="checkbox" 
                    :checked="selectedProducts.includes(index)"
                    @change="() => toggleProductSelection(index)"
                  >
                </div>
                <div v-if="product.image" class="product-image">
                  <img :src="product.image" :alt="product.name" class="product-img">
                </div>
                <div class="product-info">
                  <h4 class="product-name">{{ product.name }}</h4>
                  <div v-if="product.price" class="product-price">{{ product.price }}</div>
                  <div v-if="product.description" class="product-description">
                    {{ product.description }}
                  </div>
                  <a v-if="product.url" :href="product.url" target="_blank" class="product-link">
                    查看详情
                  </a>
                </div>
              </div>
            </div>
            <div v-else class="no-products">
              未爬取到商品信息
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.product-crawler {
  height: 100%;
}

.panel {
  background-color: white;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

/* Cookie相关样式 */
.cookie-controls {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
  flex-wrap: wrap;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
}

.btn-small {
  padding: 4px 10px;
  font-size: 12px;
  border-radius: 4px;
  cursor: pointer;
  border: 1px solid #ddd;
  background-color: #f8f9fa;
  color: #333;
}

.btn-small:hover {
  background-color: #e9ecef;
}

.btn-small:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-warning {
  background-color: #ffc107;
  color: #212529;
  border-color: #ffc107;
}

.btn-warning:hover {
  background-color: #e0a800;
}

.cookie-input-container {
  margin-top: 10px;
}

.form-input.full-width {
  width: 100%;
}

.hint-text {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
  margin-bottom: 0;
}

.cookie-status {
  font-size: 12px;
  color: #28a745;
  margin-top: 5px;
  padding: 5px;
  background-color: #d4edda;
  border-radius: 4px;
}

.panel-header {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

.panel-body {
  padding: 20px;
}

/* 表单样式 */
.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #606266;
}

.form-input {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-input:focus {
  outline: none;
  border-color: #1abc9c;
}

.full-width {
  width: 100%;
  box-sizing: border-box;
}

.form-actions {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

/* 按钮样式 */
.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-primary {
  background-color: #1abc9c;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background-color: #16a085;
}

.btn-secondary {
  background-color: #909399;
  color: white;
}

.btn-secondary:hover:not(:disabled) {
  background-color: #73777a;
}

.btn-success {
  background-color: #67c23a;
  color: white;
}

.btn-success:hover {
  background-color: #5daf34;
}

/* 日志区域 */
.crawl-logs {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.crawl-logs h4 {
  margin-top: 0;
  font-size: 14px;
  color: #606266;
}

.logs-container {
  max-height: 150px;
  overflow-y: auto;
  margin-top: 10px;
}

.log-item {
  margin: 5px 0;
  font-size: 13px;
  color: #606266;
}

/* 错误提示 */
.error {
  margin-top: 20px;
  padding: 10px;
  background-color: #fef0f0;
  color: #f56c6c;
  border-radius: 4px;
  font-size: 14px;
}

/* 爬取结果 */
.crawl-result {
  margin-top: 20px;
  padding: 15px;
  background-color: #f0f9ff;
  border-radius: 4px;
  border: 1px solid #b3d8ff;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.header-left h4 {
  margin: 0;
}

.result-header h4 {
  margin: 0;
  font-size: 16px;
  color: #409eff;
}

.result-content {
  background-color: white;
  padding: 20px;
  border-radius: 4px;
}

/* 商品网格 */
.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

/* 商品卡片 */
.product-card {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  transition: box-shadow 0.3s;
  position: relative;
}

.product-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 商品复选框 */
.product-checkbox {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 10;
}

.product-checkbox input[type="checkbox"] {
  width: 18px;
  height: 18px;
  cursor: pointer;
}

.product-image {
  text-align: center;
  margin-bottom: 10px;
}

.product-img {
  max-width: 100%;
  max-height: 200px;
  object-fit: contain;
}

.product-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.product-name {
  margin: 0;
  font-size: 16px;
  color: #303133;
  font-weight: 500;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-price {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
}

.product-description {
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
  height: 42px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-link {
  color: #409eff;
  text-decoration: none;
  font-size: 14px;
  margin-top: 5px;
  align-self: flex-start;
}

.product-link:hover {
  text-decoration: underline;
}

/* 无商品提示 */
.no-products {
  text-align: center;
  padding: 40px;
  color: #909399;
  font-size: 16px;
}
</style>